package view.usuario;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import model.entidades.Usuario;
import model.repositorio.UsuarioDAO;
import utils.Constantes;
import view.componentes.QuaseGenericoTableModel;
import view.profissional.TelaCadastrarProfissional;
import controller.ControladorExcecao;
import controller.ControladorUsuario;


public class TelaPesquisarUsuario extends JDialog implements ActionListener {

	private static final long serialVersionUID = 1L;

	private JPanel panelNorte;
	private final JPanel panelCentro = new JPanel();
	private JPanel panelSul;

	private JLabel lblPesquisarUsuarios;
	private JLabel lblResultadosPesquisa;
	private JLabel lblTextoDaPesquisa;
	private JButton btnCancelar;

	private JComboBox<String> comboBox;

	private JRadioButton rdbtnAtivo;
	private JRadioButton rdbtnInativo;
	private JRadioButton rdbtnAmbos;

	private JTable tableResultadosPesquisa;

	private QuaseGenericoTableModel<Usuario> pesquisaTableModel;

	private ControladorUsuario controladorUsuario;

	private ButtonGroup grupoSituacao;


	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}else{
							UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
						}
					}
					TelaPesquisarUsuario window = new TelaPesquisarUsuario();
					window.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});		
	}

	/**
	 * Create the dialog.
	 */
	public TelaPesquisarUsuario() {
		controladorUsuario = new ControladorUsuario(null);
		inicializaComponentes();
		realizaPesquisa(UsuarioDAO.TIPO_TODOS, UsuarioDAO.SITUACAO_ATIVOS);
	}

	private void inicializaComponentes() {
		setBounds(100, 100, 600, 450);
		setResizable(false);
		setModal(true);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		panelCentro.setBackground(Color.WHITE);
		panelCentro.setBorder(new EmptyBorder(5, 0, 5, 5));
		getContentPane().add(panelCentro, BorderLayout.CENTER);

		lblResultadosPesquisa = new JLabel("Resultados da Pesquisa");
		lblResultadosPesquisa.setBorder(new EmptyBorder(0, 0, 0, 5));
		lblResultadosPesquisa.setHorizontalAlignment(SwingConstants.LEFT);
		lblResultadosPesquisa.setBackground(Color.LIGHT_GRAY);
		lblResultadosPesquisa.setFont(new Font("Tahoma", Font.PLAIN, 14));

		lblTextoDaPesquisa = new JLabel("Exibir:");

		comboBox = new JComboBox<String>();
		comboBox.addActionListener(this);
		comboBox.setBackground(Color.WHITE);
		comboBox.setModel(new DefaultComboBoxModel<String>(Constantes.TIPOS_PESQUISA_USUARIO));

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setToolTipText("Clique duas vezes na linha para exibir o Usu\u00E1rio.");
		scrollPane.setBackground(Color.WHITE);
		scrollPane.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));

		JSeparator separator = new JSeparator();

		rdbtnAtivo = new JRadioButton("Ativo");
		rdbtnAtivo.setBackground(Color.WHITE);
		rdbtnAtivo.addActionListener(this);

		rdbtnInativo = new JRadioButton("Inativos");
		rdbtnInativo.setBackground(Color.WHITE);
		rdbtnInativo.addActionListener(this);

		rdbtnAmbos = new JRadioButton("Ambos");
		rdbtnAmbos.setBackground(Color.WHITE);
		rdbtnAmbos.addActionListener(this);
		
		grupoSituacao = new ButtonGroup();
		grupoSituacao.add(rdbtnAtivo);
		grupoSituacao.add(rdbtnInativo);
		grupoSituacao.add(rdbtnAmbos);
		grupoSituacao.setSelected(rdbtnAtivo.getModel(), true);
		
		GroupLayout gl_panelCentro = new GroupLayout(panelCentro);
		gl_panelCentro.setHorizontalGroup(
				gl_panelCentro.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panelCentro.createSequentialGroup()
						.addGap(9)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
						.addGap(3))
						.addGroup(gl_panelCentro.createSequentialGroup()
								.addContainerGap(8, Short.MAX_VALUE)
								.addGroup(gl_panelCentro.createParallelGroup(Alignment.TRAILING)
										.addGroup(gl_panelCentro.createSequentialGroup()
												.addGap(4)
												.addComponent(lblResultadosPesquisa, GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
												.addContainerGap())
												.addGroup(gl_panelCentro.createSequentialGroup()
														.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
																.addGroup(gl_panelCentro.createSequentialGroup()
																		.addComponent(lblTextoDaPesquisa)
																		.addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addComponent(rdbtnAtivo)
																		.addGap(12)
																		.addComponent(rdbtnInativo)
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addComponent(rdbtnAmbos))
																		.addComponent(separator, GroupLayout.PREFERRED_SIZE, 565, GroupLayout.PREFERRED_SIZE))
																		.addGap(4))))
				);
		gl_panelCentro.setVerticalGroup(
				gl_panelCentro.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelCentro.createSequentialGroup()
						.addGap(10)
						.addGroup(gl_panelCentro.createParallelGroup(Alignment.TRAILING)
								.addGroup(gl_panelCentro.createSequentialGroup()
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
												.addComponent(lblTextoDaPesquisa)
												.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE))
												.addGap(12))
												.addGroup(gl_panelCentro.createSequentialGroup()
														.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
																.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
																		.addComponent(rdbtnInativo)
																		.addComponent(rdbtnAmbos))
																		.addComponent(rdbtnAtivo))
																		.addGap(18)))
																		.addComponent(separator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(lblResultadosPesquisa)
																		.addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE)
																		.addContainerGap())
				);

		
		pesquisaTableModel = new QuaseGenericoTableModel<Usuario>(Usuario.class, new ArrayList<Usuario>(), Constantes.COLUNAS_PESQUISA_USUARIO);
		tableResultadosPesquisa = new JTable(pesquisaTableModel);
		tableResultadosPesquisa.addMouseListener(new MouseAdapter() {  
		    public void mouseClicked(MouseEvent e) {  
		    	cliqueTabela(e);
		    }  
		});  
		tableResultadosPesquisa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableResultadosPesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
		tableResultadosPesquisa.getColumnModel().getColumn(1).setMaxWidth(110);
		tableResultadosPesquisa.getColumnModel().getColumn(2).setPreferredWidth(60);
		tableResultadosPesquisa.getColumnModel().getColumn(2).setMaxWidth(60);

		scrollPane.setViewportView(tableResultadosPesquisa);
		panelCentro.setLayout(gl_panelCentro);
		{
			panelSul = new JPanel();
			panelSul.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(panelSul, BorderLayout.SOUTH);
			{
				btnCancelar = new JButton("Sair");
				btnCancelar.setActionCommand("Cancel");
				btnCancelar.addActionListener(this);
				panelSul.add(btnCancelar);
			}
		}
		{
			panelNorte = new JPanel();
			panelNorte.setForeground(Color.WHITE);
			panelNorte.setBackground(Color.BLUE);
			getContentPane().add(panelNorte, BorderLayout.NORTH);

			lblPesquisarUsuarios = new JLabel("Pesquisar Usu\u00E1rios");
			lblPesquisarUsuarios.setForeground(Color.WHITE);
			lblPesquisarUsuarios.setFont(new Font("Tahoma", Font.BOLD, 18));
			panelNorte.add(lblPesquisarUsuarios);
		}

	}//inicializaComponentes()
	
	private void cliqueTabela(MouseEvent e) {
		if (e.getClickCount() == 2) {  
            Point p = e.getPoint();  
            int row = tableResultadosPesquisa.rowAtPoint(p);
            Usuario usuario = pesquisaTableModel.getItemLinha(row);
            if (usuario.getTipoPerfil().equalsIgnoreCase(Constantes.TIPO_PERFIL_OPERADOR)) {
            	new TelaCadastrarUsuario(usuario).setVisible(true);
			} else {
				new TelaCadastrarProfissional(usuario).setVisible(true);
			}
            
        } 
	}

	@Override
	public void actionPerformed(ActionEvent event) {

		String comando = event.getActionCommand();
		
		if(comando.equalsIgnoreCase(btnCancelar.getActionCommand())){
			this.dispose();
		} else {
			String tipo = "";
			String situacao = "";
			
			switch (comboBox.getSelectedIndex()) {
			case 0:
				tipo = UsuarioDAO.TIPO_TODOS;
				break;
			case 1:
				tipo = UsuarioDAO.TIPO_PROFISSIONAL;
				break;
			case 2:
				tipo = UsuarioDAO.TIPO_OPERADOR;
				break;
			default:
				break;
			}
			
			if(rdbtnAtivo.isSelected()) {
				situacao = UsuarioDAO.SITUACAO_ATIVOS;
			} else if (rdbtnInativo.isSelected()) {
				situacao = UsuarioDAO.SITUACAO_INATIVOS;
			} else if (rdbtnAmbos.isSelected()) {
				situacao = UsuarioDAO.SITUACAO_TODOS;
			}
			
			realizaPesquisa(tipo, situacao);
			
		}
	}
	
	private void realizaPesquisa(String tipo, String situacao) {
		pesquisaTableModel.limpar();
		try {
			List<Usuario> lista = controladorUsuario.pesquisarUsuario(tipo, situacao);
			pesquisaTableModel = new QuaseGenericoTableModel<Usuario>(Usuario.class, lista, Constantes.COLUNAS_PESQUISA_USUARIO);
			tableResultadosPesquisa.setModel(pesquisaTableModel);
			tableResultadosPesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
			tableResultadosPesquisa.getColumnModel().getColumn(1).setMaxWidth(110);
			tableResultadosPesquisa.getColumnModel().getColumn(2).setPreferredWidth(60);
			tableResultadosPesquisa.getColumnModel().getColumn(2).setMaxWidth(60);
			
		} catch (ControladorExcecao e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "Pesquisa", JOptionPane.PLAIN_MESSAGE );
		}
	}
}
